package getWay

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/manoshi/go-util/const/GetWay"
	"gitee.com/manoshi/go-util/log"
	"github.com/gin-gonic/gin"
	"net"
	"strings"
	"time"
)

func GetCurrentUserId(c *gin.Context) (int32, bool) {
	userId, b := c.Get(GetWay.CurrentUserIdKey)
	if b {
		transUserId := userId.(int32)
		return transUserId, b
	}
	return 0, b
}

type AdminResponse struct {
	code  int
	msg   string
	Admin Admin
}

type Admin struct {
	Id           int32
	Name         string
	LoginAccount string
}

const requestBodyKey = "requestBody"

func BindRequestBody(c *gin.Context, param interface{}) error {
	err := c.ShouldBindJSON(param)
	if err != nil {
		if strings.Contains(err.Error(), "cannot unmarshal") {
			switch err.(type) {
			case *json.UnmarshalTypeError:
				e := (err).(*json.UnmarshalTypeError)
				return errors.New(fmt.Sprintf("[%s]格式不对，请检查", e.Field))
			default:
				return errors.New("参数格式不对，请检查")
			}
		} else if err.Error() == "EOF" {
			return errors.New("json格式不正确")
		} else {
			return err
		}
	}
	bytes, err := json.Marshal(param)
	c.Set(requestBodyKey, string(bytes))
	return err
}

func GetParams(c *gin.Context) string {
	rd := ""
	params := c.Request.URL.Query().Encode()
	if params != "" {
		rd += params
	}
	ad := c.GetString(requestBodyKey)
	if ad != "" {
		rd += ad
	}
	return rd
}

func GetServerIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}
	for _, addr := range addrs {
		ipAddr, ok := addr.(*net.IPNet)
		if !ok {
			continue
		}
		if ipAddr.IP.IsLoopback() {
			continue
		}
		if !ipAddr.IP.IsGlobalUnicast() {
			continue
		}
		return ipAddr.IP.String()
	}
	return ""
}

func GetClientIP(c *gin.Context) string {
	ip := c.ClientIP()
	return ip
}

func GetURL(c *gin.Context) string {
	url := c.Request.URL.Path
	return url
}
func GetMethod(c *gin.Context) string {
	method := c.Request.Method
	return method
}
func SetStartTime(c *gin.Context) {
	c.Set(GetWay.StartTimeKey, time.Now().UnixNano())
	logStart(c)
}
func GetStartTime(c *gin.Context) int64 {
	startTime := c.GetInt64(GetWay.StartTimeKey)
	return startTime
}

func logStart(c *gin.Context) {
	log.Info(fmt.Sprintf("开始 %s %s %s %s", GetMethod(c), GetURL(c), GetToken(c), GetClientIP(c)))
}
